package com.paisheng.justlife.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.paisheng.justlife.R;
import com.paisheng.justlife.appliction.MyApplication;
import com.paisheng.justlife.bean.ComBean;
import com.paisheng.justlife.bean.Waste;
import com.paisheng.justlife.common.MenuType;
import com.paisheng.justlife.common.SerialNumber;
import com.paisheng.justlife.service.SerialService;
import com.paisheng.justlife.utils.CRCUtils;
import com.paisheng.justlife.utils.DeviceInfoUtils;
import com.paisheng.justlife.utils.MyFunc;
import com.paisheng.justlife.utils.SerialPortUtils;
import com.paisheng.justlife.utils.SharedPreferencesHelper;
import com.paisheng.justlife.utils.SubSrtingUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 投递开箱页面
 */
public class BinOpenActivity extends Activity {

    private ImageView iv;
    private Button ivBtn;
    private TextView tvTime, tv;
    private Timer timer = new Timer();
    private SerialPortUtils serialPortUtils;
    private String sMsg;
    private int recLen = 120;
    private boolean flag = false;
    private String openClass;
    private String phone;
    private Intent intent;
    private SharedPreferencesHelper spfh;
    private String userPhone, facility;
    private List<Waste> wasteList = new ArrayList<>();
    private List<Waste> facilityWaste = new ArrayList<>();
    private String facilityNumber;
    String wasteStr;
    String jsonString;
    boolean ifOpen = true;
    MyApplication context;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bin_open);
        eventListening();
        initView();
        removeThePeel();
    }


    @Override
    protected void onResume() {
        super.onResume();
        timer.schedule(task, 1000, 1000);
    }


    private void initView() {
        iv = (ImageView) findViewById(R.id.iv);
        ivBtn = (Button) findViewById(R.id.iv_btn);
        tvTime = (TextView) findViewById(R.id.tv_time);
        tv = (TextView) findViewById(R.id.tv);
        spfh = new SharedPreferencesHelper(this, "CAST_MESSAGE");
        tvTime.setText(recLen + "");
        facilityNumber = DeviceInfoUtils.getMacAddress(this);
        intent = new Intent(context, SerialService.class);
        context.stopService(intent);

    }

    private void removeThePeel() {

        intent = getIntent();
        openClass = intent.getStringExtra("openClass");
        phone = intent.getStringExtra("phone");
        if (openClass.equals("metal")) {   //打开金属箱门
            openBoor(SerialNumber.NET_WEIGHT_METAL, R.drawable.bg_tips_metal);
        }
        if (openClass.equals("plastic")) { //打开塑料箱门
            openBoor(SerialNumber.NET_WEIGHT_PLASTIC, R.drawable.bg_tips_plastic);
        }
        if (openClass.equals("clothes")) { //打开纺织物箱门
            openBoor(SerialNumber.NET_WEIGHT_CLOTHES, R.drawable.bg_tips_clothes);
        }

        if (openClass.equals("paper")) { //----------纸类暂无图片 打开纸类箱门
            openBoor(SerialNumber.NET_WEIGHT_PAPER, R.drawable.bg_tips_paper);
        }

        if (openClass.equals("harmful")) { //开发有害垃圾箱门

        }
    }

    private void openBoor(String netWeightMetal, int p) {
        serialPortUtils.sendSerialPort(netWeightMetal);//去皮
        iv.setBackgroundResource(p); //切换图片
        tv.setText("系统正在计算重量，请稍后…………");
    }

    // 串口回调监听
    private void eventListening() {
        context = (MyApplication) getApplicationContext();
        serialPortUtils = context.serialPortUtils;
        this.serialPortUtils.setOnDataReceiveListener(new SerialPortUtils.OnDataReceiveListener() {
            @Override
            public void onDataReceive(ComBean ComRecData) {
                sMsg = MyFunc.ByteArrToHex(ComRecData.bRec);
                System.out.println("BinOpenActivity" + sMsg);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //计算称重并保存
                        if (sMsg.indexOf(SerialNumber.RETURN_WEIGH) != -1) {
                            if(SubSrtingUtils.parseHex4(sMsg)<0){
                                String str =  sMsg.substring(0, 10)+"0000";
                                byte[] bOutArray = MyFunc.HexToByteArr(str);
                                int crc16 = CRCUtils.calcCrc16(bOutArray,bOutArray.length);
                                sMsg = str+String.format("0x%04x", crc16).replace("0x", "").toUpperCase();
                            }
                            if (SubSrtingUtils.parseHex4(sMsg) >= 0) {
                                if (sMsg.indexOf(SerialNumber.RETURN_WEIGH_PLASTIC) != -1
                                        && sMsg.equals(SubSrtingUtils.getStringVerify(sMsg))) {
                                    calcAndreCord(sMsg, MenuType.PLASTIC, MenuType.PLASTIC_PRICE);
                                }
                                if (sMsg.indexOf(SerialNumber.RETURN_WEIGH_CLOTHES) != -1
                                        && sMsg.equals(SubSrtingUtils.getStringVerify(sMsg))) {
                                    calcAndreCord(sMsg, MenuType.CLOTHES, MenuType.CLOTHES_PRICE);
                                }
                                if (sMsg.indexOf(SerialNumber.RETURN_WEIGH_METAL) != -1
                                        && sMsg.equals(SubSrtingUtils.getStringVerify(sMsg))) {
                                    calcAndreCord(sMsg, MenuType.METAL, MenuType.METAL_PRICE);
                                }
                                if (sMsg.indexOf(SerialNumber.RETURN_WEIGH_PAPER) != -1
                                        && sMsg.equals(SubSrtingUtils.getStringVerify(sMsg))) {
                                    calcAndreCord(sMsg, MenuType.PAPER, MenuType.PAPER_PRICE);
                                }

                            } else {
                                tv.setText("称重错误串号" + sMsg);
                            }

                        } else {

                            switch (sMsg) {
                                case (SerialNumber.RETURN_WEIGHT_METAL): //金属去皮成功
                                    openAllAndclick(SerialNumber.OPEN_METAL, SerialNumber.CLOSE_METAL);
                                    break;
                                case (SerialNumber.RETURN_WEIGHT_PLASTIC): //塑料去皮成功
                                    openAllAndclick(SerialNumber.OPEN_PLASTIC, SerialNumber.CLOSE_PLASTIC);
                                    break;
                                case (SerialNumber.RETURN_WEIGHT_CLOTHES): //纺织物去皮成功
                                    openAllAndclick(SerialNumber.OPEN_CLOTHES, SerialNumber.CLOSE_CLOTHES);
                                    break;
                                case (SerialNumber.RETURN_WEIGHT_PAPER): //纸类去皮成功
                                    openAllAndclick(SerialNumber.OPEN_PAPER, SerialNumber.CLOSE_PAPER);
                                    break;
                                case (SerialNumber.RETURN_OPEN_METAL):
                                    tv.setText("金属箱门已打开，请文明投递");
                                    flag = true;
                                    break;
                                case (SerialNumber.RETURN_OPEN_PLASTIC):
                                    tv.setText("塑料箱门已打开，请文明投递");
                                    flag = true;
                                    break;
                                case (SerialNumber.RETURN_OPEN_CLOTHES):
                                    tv.setText("纺织物箱门已打开，请文明投递");
                                    flag = true;
                                    break;
                                case (SerialNumber.RETURN_OPEN_PAPER):
                                    tv.setText("纸类箱门已打开，请文明投递");
                                    flag = true;
                                    break;
                                case (SerialNumber.RETURN_CLOSE_METAL): //金属门关闭成功
                                    if (ifOpen) {
                                        BinOpenActivity.this.serialPortUtils.sendSerialPort(SerialNumber.WEIGH_METAL);
                                    }
                                    break;
                                case (SerialNumber.RETURN_CLOSE_PLASTIC): //塑料门关闭成功
                                    if (ifOpen) {
                                        BinOpenActivity.this.serialPortUtils.sendSerialPort(SerialNumber.WEIGH_PLASTIC);
                                    }
                                    break;
                                case (SerialNumber.RETURN_CLOSE_CLOTHES): //纺织物门关闭成功
                                    if (ifOpen) {
                                        BinOpenActivity.this.serialPortUtils.sendSerialPort(SerialNumber.WEIGH_CLOTHES);
                                    }
                                    break;
                                case (SerialNumber.RETURN_CLOSE_PAPER): //纸类门关闭成功
                                    if (ifOpen) {
                                        BinOpenActivity.this.serialPortUtils.sendSerialPort(SerialNumber.WEIGH_PAPER);
                                    }
                                    break;
                                default:
                                    tv.setText("错误串号" + sMsg);
                                    break;
                            }

                        }
                    }
                });
            }
        });

    }

    private void openAllAndclick(String openMetal, String closeMetal) {
        tv.setText("箱门正在打开……");
        BinOpenActivity.this.serialPortUtils.sendSerialPort(openMetal); //金属开箱
        btnCloseSerialNumber(closeMetal); //点击事件
    }


    private void calcAndreCord(String msg, String name, String resultPrice) {

        if (spfh.contain(phone)) {
            userPhone = (String) spfh.getSharedPreference(phone, String.class);
            wasteList = JSON.parseArray(userPhone, Waste.class);
        }
        if (spfh.contain(facilityNumber)) {
            facility = (String) spfh.getSharedPreference(facilityNumber, String.class);
            facilityWaste = JSON.parseArray(facility, Waste.class);
        }

        String weigh = SubSrtingUtils.getWeigh(msg);
        String totalMoney = SubSrtingUtils.getTotalmoney(weigh, resultPrice);
        Waste waste = new Waste("", name, weigh, resultPrice, totalMoney, false);
        // 用户存储
        wasteList.add(waste);
        wasteStr = JSON.toJSONString(wasteList);
        spfh.put(phone, wasteStr);

        //设备存储
        facilityWaste.add(waste);
        jsonString = JSON.toJSONString(facilityWaste);
        spfh.put(facilityNumber, jsonString);

        intent = new Intent(context, SerialService.class);
        context.startService(intent);

        intent = new Intent(BinOpenActivity.this, FinishActivity.class);
        intent.putExtra("phone", phone);
        startActivity(intent);

    }


    private void btnCloseSerialNumber(final String closeMetal) {
        ivBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (flag) {
                    tv.setText("箱门正在关闭，请稍等……");
                    serialPortUtils.sendSerialPort(closeMetal);
                }
            }
        });
    }

    public TimerTask task = new TimerTask() {
        @Override
        public void run() {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    recLen--;
                    tvTime.setText("" + recLen);
                    if (recLen <= 0) {
                        startActivity(new Intent(BinOpenActivity.this, MainActivity.class));

                        ifOpen = false;
                        switch (sMsg) {
                            case (SerialNumber.RETURN_OPEN_METAL):
                                serialPortUtils.sendSerialPort(SerialNumber.CLOSE_METAL);
                                break;
                            case (SerialNumber.RETURN_OPEN_PAPER):
                                serialPortUtils.sendSerialPort(SerialNumber.CLOSE_PAPER);
                                break;
                            case (SerialNumber.RETURN_OPEN_PLASTIC):
                                serialPortUtils.sendSerialPort(SerialNumber.CLOSE_PLASTIC);
                                break;
                            case (SerialNumber.RETURN_OPEN_CLOTHES):
                                serialPortUtils.sendSerialPort(SerialNumber.CLOSE_CLOTHES);
                                break;
                        }
                        intent = new Intent(context, SerialService.class);
                        context.startService(intent);
                        timer.cancel();
                    }

                }
            });

        }
    };

    @Override
    protected void onPause() {
        super.onPause();
        timer.cancel();
        finish();
    }


}
